# _*_ coding: utf-8 _*_
#需要的库
import	os
import	sys
import	logging
import	string
import	time
import	re
from	nltk.stem.porter import PorterStemmer  
from	Tkinter import *
from	ScrolledText import *
import	tkMessageBox
from	tkFileDialog import *
import	fileinput
from	YDdict import *
#全局变量
dict = {}
idict = {}
udict = {}
pwd = None
filename = None
saveFileName = None
#函数
def getpwd():
	pwd = sys.path[0]
	if os.path.isfile(pwd):
		pwd = os.path.dirname(pwd)
	return pwd
'''---------------------------------------------------------------------------
索引词典:
	用户词典包含word、mean两项，word为单词，mean为词义。词义已'\n'换行。
-------------------------------------------------------------------------------'''
def lodeindexdict():
	global idict
	fDictPath = pwd + '\idict.idic'
	fDict = open( fDictPath,'r')
	lines = fDict.readlines()
	for line in lines:  
		line = line.strip()
		if not len(line) or line.startswith('#'):       #判断是否是空行或注释行  
			continue 
		try:
			[word,mean] = line.split('\t')
			idict[word] = mean
		except:
			logging.warning(line)
'''---------------------------------------------------------------------------
主词典:
	用户词典包含word、mean两项，word为单词，mean为词义。词义已'\n'换行。
-------------------------------------------------------------------------------'''
def lodedict():
	global dict
	fDictPath = pwd + '\oxford-ec.dict'
	fDict = open( fDictPath,'r')
	lines = fDict.readlines()
	for line in lines:  
		line = line.strip()
		if not len(line) or line.startswith('#'):       #判断是否是空行或注释行  
			continue 
		try:
			[word,mean] = line.split('\t')
			dict[word] = mean
		except:
			logging.warning(line)
'''---------------------------------------------------------------------------
用户词典:
	用户词典包含word、learn、num三项，word为单词，learn为记忆程度，分别为0（不会）、
	1（临时记忆）、2（一般记忆）、3（深度记忆），num为已见到过的次数。
-------------------------------------------------------------------------------'''
def lodeuserdict():
	global udict
	fDictPath = pwd + '\user_learn.udic'
	fDict = open( fDictPath,'r+')
	lines = fDict.readlines()
	for line in lines:  
		line = line.strip()
		if not len(line) or line.startswith('#'):       #判断是否是空行或注释行  
			continue 
		try:
			[word,learn,num] = line.split('\t')
			udict[word] = [string.atoi(learn),string.atoi(num)]
		except:
			logging.warning(line)
			
def adduserdict(word):
	global udict
	if not udict.has_key(word):
		udict[word] = (0,1)
		logging.warning('insert word '+word)

'''---------------------------------------------------------------------------
分词器:
	从一句话中取得单词。
-------------------------------------------------------------------------------'''
def l2w(line):
	pattern = r'''(?x) [\w-]+ | [\W]? '''
	words = re.findall(pattern,line)
	return words
	
def imean(w):
	m = ''
	w = filter(str.isalpha,w)
	if len(w):
		w = PorterStemmer().stem_word(w).lower()
		if not udict.has_key(w):
			if idict.has_key(w):
				m =  idict[w]
				#print "1"
			#else:
				#m = YDdict().translate(w)
				#time.sleep(0.1)
				#print "2"+m
			'''try:
				#m = idict[w.lower()]
				m = YDdict().translate(w)
				
				print '1.'+m
				#w=w.replace(w1,'%s (%s)'%(w1,mean))
			except:
				m = ''
			'''
	return m

class editor:
	def	__init__(self,rt):
		self.t = rt
		self.t.title("NotDict")
		self.t.geometry('700x480+%d+%d'%((self.t.winfo_screenwidth()-700)/2,(self.t.winfo_screenheight()-540)/2))
		#菜单
		self.bar=Menu(rt)
		#File菜单
		self.filem=Menu(self.bar,tearoff=0)
		self.filem.add_command(label="打开",command=self.openfile)
		#self.filem.add_command(label="新建",command=self.neweditor)
		self.filem.add_command(label="另存为",command=self.savefile)
		self.filem.add_command(label="关闭",command=self.close)
		#翻译菜单
		self.tranm=Menu(self.bar,tearoff=0)
		self.tranm.add_command(label="翻译",command=self.transfer)
		#help菜单
		self.helpm=Menu(self.bar,tearoff=0)
		self.helpm.add_command(label="关于",command=self.about)
		#根菜单
		self.bar.add_cascade(label="文件",menu=self.filem)
		self.bar.add_cascade(label="翻译",menu=self.tranm)
		self.bar.add_cascade(label="帮助",menu=self.helpm)
		self.t.config(menu=self.bar)
		#右键弹出菜单
		self.popm = Menu(tearoff=0)
		self.popm.add_command(label="打开",command=self.openfile)
		
		
		self.dict=Frame(self.t)
		self.dict.pack(fill=Y,side =RIGHT)
		#顶部框架
		self.top=Frame(self.t)
		self.top.pack(fill=X)
		Button(self.top,text=" 打开 ",command=self.openfile).pack(side = LEFT)
		self.e=Entry(self.top)
		self.e.pack(side = LEFT,fill = X,expand=1)
		Button(self.top,text=" 原文 ",command=self.original).pack(side = LEFT)
		Button(self.top,text=" 翻译 ",command=self.transfer).pack(side = RIGHT)
		
		#下面框架
		self.bottom=Frame(self.t)
		self.bottom.pack(fill=BOTH,expand=1)
		self.st=ScrolledText(self.bottom,background="white",wrap=WORD,state="normal")
		self.st.pack(side=LEFT,fill=BOTH,expand=1)
		self.st.tag_config('high_color_1',foreground = 'blue')
		self.st.tag_config('high_color_2',foreground = 'red')
		self.st.bind('<Button-3>',self.onRightClick)
		self.st.bind('<Button-1>',self.onDBClick)
		
		#词典框架
		#Label(self.dict,text="[NotDict] = [Not Only The Dict]\n开发者：ldy 网站：www.ccuos.com").pack(side = TOP,fill = X)
		self.dcx=Frame(self.dict)
		self.dcx.pack(side = TOP,fill = X)
		self.de=Entry(self.dcx)
		self.de.pack(side = LEFT,fill = X,expand=1)
		self.de.bind('<Return>',self.query)
		self.db=Button(self.dcx,text=" 查询 ")
		self.db.pack(side = LEFT,fill = X)
		self.db.bind('<Button-1>',self.query)
		self.dst=ScrolledText(self.dict,background="wheat",wrap=WORD,state="disable",width=36)
		self.dst.pack(side=TOP,fill=Y,expand=1)
		self.dst.tag_config('high_color_1',foreground = 'blue')
		self.dst.tag_config('high_color_2',foreground = 'red')
		self.dst.tag_config('high_color_3',foreground = 'green')
		self.dst.tag_config('high_color_4',foreground = 'yellow')
		self.dst.tag_config('high_color_5',foreground = 'white')
		self.dwa=Frame(self.dict)
		self.dwa.pack(side = TOP,fill = X)
		self.dww=Label(self.dwa,text='')
		self.dww.pack(side = TOP,fill = X)
		self.dl = IntVar()
		self.dv0 = Radiobutton(self.dwa,variable=self.dl,value=0,command=self.setuserlearn,text="不会")
		self.dv0.pack(side = LEFT)
		self.dv1 = Radiobutton(self.dwa,variable=self.dl,value=1,command=self.setuserlearn,text="见过")
		self.dv1.pack(side = LEFT)
		self.dv2 =Radiobutton(self.dwa,variable=self.dl,value=2,command=self.setuserlearn,text="记住了")
		self.dv2.pack(side = LEFT)
		self.dv3 =Radiobutton(self.dwa,variable=self.dl,value=3,command=self.setuserlearn,text="倒背如流")
		self.dv3.pack(side = LEFT)
	#私有函数
	def close(self):
		self.t.destroy()
#用户词典设置
	def setuserlearn(self):
		global udict
		w = self.de.get()
		w = filter(str.isalpha,w)
		if (not udict.has_key(w)) and len(w):
			udict[w] = (0,self.dl)
			logging.warning('insert word '+w)
		else:
			logging.warning('No word '+w)
	'''def callCheckbutton(self):
		if self.v.get():
			print self.v.get()
		else:
			print self.v.get()'''
	
	def mshow(self):
		w = self.de.get()
		w = filter(str.isalpha,w)
		m = ''
		if len(w):
			try:
				m = dict[w.lower()]
				#m = YDdict().translate(w)
				#w=w.replace(w1,'%s (%s)'%(w1,mean))
			except:
				m = YDdict().translate(w)
		ms = m.split('\\n')
		self.dst.config(state="normal")
		self.dst.delete(0.0,END)
		for m in ms:
			if m[0:1].isdigit():
				self.dst.insert(END,m+'\n','high_color_2')
			elif m[0:1]=='(':
				self.dst.insert(END,m+'\n','high_color_2')
			elif m[0:1]=='*':
				self.dst.insert(END,m+'\n')
			else:
				self.dst.insert(END,m+'\n','high_color_1')
		self.dst.config(state="disable")
		self.freshdv(w)
	
	def query(self,bind):
		self.mshow()
		
	def onRightClick(self,event):
		self.popm.post(event.x_root,event.y_root)
#刷新单选按钮
	def freshdv(self,w):
		if udict.has_key(w):
			v = udict[w]
			self.dl = v[0]
		else:
			self.dl = 0
		if self.dl == 0:
			self.dv0.select()
		elif self.dl == 1:
			self.dv1.select()
		elif self.dl == 2:
			self.dv2.select()
		elif self.dl == 3:
			self.dv3.select()
		if self.dl:
			self.dww.config(text="%s: 已经见过%d次！"%(w,v[1]))
		else:
			self.dww.config(text="%s: 新发现一个不认识的单词！"%(w))
#双击单词事件
	def onDBClick(self,event):
		sn = self.st.index(CURRENT)
		s0 = sn
		s1 = sn
		while self.st.get(s0).isalpha():
			a = s0.split('.')
			if (string.atoi(a[1])==0):
				break
			s0='%s.%d'%(a[0],(string.atoi(a[1])-1))
		a = s0.split('.')
		if string.atoi(a[1]):
			s0='%s.%d'%(a[0],(string.atoi(a[1])+1))
		while self.st.get(s1).isalpha():
			a = s1.split('.')
			s1='%s.%d'%(a[0],(string.atoi(a[1])+1))
		w = self.st.get(s0,s1).encode('utf-8')
		w = filter(str.isalpha,w)
		self.de.delete(0,END)
		self.de.insert(0,w)
		self.mshow()
		
	def openfile(self):
		global filename
		oname=askopenfilename(filetypes=[("Text file","*.txt"),("All file","*.*")])
		filename = oname
		if len(filename):
			self.st.config(state="normal")
			self.st.delete(0.0,END)
			self.e.delete(0,END)
			self.e.insert(0,filename)
			#if oname:
			for	line in fileinput.input(oname):
				self.st.insert(END,line)
			self.t.title(oname)

	def savefile(self):
		sname=asksaveasfilename()
		if sname:
			ofp=open(sname,"w")
			text = self.st.get(0.0,END).encode('utf-8')
			#print text.encode('utf-8')
			ofp.write(text)
			ofp.flush()
			ofp.close()
			self.t.title(sname)

#载入原文			
	def original(self):
		global filename
		self.st.config(state="normal",background="white")
		if filename:
			self.st.delete(0.0,END)
			for	line in fileinput.input(filename):
				self.st.insert(END,line)

#文章单词翻译
	def transfer(self):
		self.st.config(state="normal",background="LightCyan")
		a = self.st.index(END).split('.')
		line_end = string.atoi(a[0])
		for line in range(0,line_end,1):
			str = self.st.get('%d.0'%line,'%d.end'%line)
			try:
				str = str.encode('utf-8')
			except:
				str = str
			words = l2w(str)
			self.st.delete('%d.0'%line,'%d.end'%line)
			for word in words:
				self.st.insert('%d.end'%line,'%s'%word)
				mean = imean(word)
				if len(mean):
					self.st.insert('%d.end'%line,'(%s)'%mean,'high_color_1')
		self.st.config(state="disable")
		
	def about(self):
		tkMessageBox.showinfo("Notdict","Notdict is \"Not Only The Dict\"!\nNotdict 的意思是“不仅仅是词典”！\n版本：0.01\n开发者：ldy\n网站：www.ccuos.com")
#主程序
if __name__ == "__main__":
	pwd = getpwd()
	root = Tk()
	editor(root)
	lodeindexdict()
	lodeuserdict()
	lodedict()
root.mainloop()